<template>
  <div class="welcome_page">
    <div>
      <van-nav-bar
      title="欢迎使用近聘"
      
    />
    <van-row class="avatar_login wehead" v-if="allUserInfo?.id">
      <van-col span="6" class="userImg">
        <van-image
          class="img"
          width="60"
          height="60"
          :src="allUserInfo.avatar ? allUserInfo.avatar : logoImg"
          round
          fit="cover"
        />
      </van-col>
      <van-col span="11" class="userLogin">
        <!--            <div class="isLogin" v-else>{{allUserInfo.id.substring(0,15)}}</div>-->
        <template>
          <div class="nick_name van-ellipsis">昵称: {{ allUserInfo.nick_name || '近聘' }}</div>
          <div class="account">账号: {{ allUserInfo.ids || '近聘' }}</div>
          <div class="account">手机: {{ allUserInfo.mobile || '' }}</div>
        </template>
      </van-col>
      <van-col span="7" class="userDetail">
        <div class="jinpinHelper" @click="$router.push('/login?redirect=1')">切换账号登入 ></div>
      </van-col>
    </van-row>
    <van-cell-group>
      <!-- 判断是否做了企业认证, todo      -->
      <van-cell
        title="查看您扫码的公司招聘信息或者关注该公司"
        is-link
        center
        icon="fire-o"
        @click="toCompanyPage(companyId, group_state)"
        :label="`该公司的信息：${authStatus[group_state]}`"
        class="hot_operation"
      />
     <!-- <van-cell
        title="添加您扫码的好友"
        is-link
        center
        @click='add_friend()'
        :label="`该好友的信息：${authStatus[person_state]}`"
      /> -->
<!--      <van-cell
        title="关注店铺"
        is-link
      />-->
      <!-- <button @click="getUserLocation">获取位置</button>
      <div>
        纬度: {{ location }}
      </div> -->
      <van-cell
        title="注册"
        center
        is-link label="注册可使用更多功能"
        @click="toRegisterPage"
      />
      <van-cell
        v-if="!this.allUserInfo?.id"
        title="登录"
        is-link
        label="已有账号？请直接登录"
        :to="'/login?redirect=1'"
        center
      />
      <van-cell
        title="使用助手"
        is-link
        label="有疑问，请查看使用助手"
         @click="toHelper"
        center
      />
      <van-cell
        title="领取股份"
        is-link
        label="每天都可以扫我的近聘推广海报，或者点我的近聘推广链接，领取股份，享受分红"
        @click="toReceivedStockPage(stock.unTakeNum, 'no')"
        center
      />
    </van-cell-group>
    <comDownload></comDownload>
    </div>
    

  </div>
</template>

<script>
import {Dialog, Toast} from "vant";
import comDownload from "./comDownload";
import {mapGetters} from "vuex";
import stock from "@/api/stock.js"
const authStatus= {
  '0': '未认证',
  '1': '审核中',
  '2': '已成功认证',
  '3': '认证失败',
  '': '未知',
  undefined: '未知',
};
const sourceTypeObj = {
  L: '网址链接',
  V: '竖版海报',
  H: '横版海报'
}
export default {
  name: "welcome",
  components: {
    comDownload,
  },

  data(){
    return {
      // qodeType:0,
      location:null,
      authStatus,
      recommendID: '',
      companyId: '',
      person_state: '',
      group_state: '',
      account: '',
      channelId : '',
      channelName : '',
      source_type: '',
      stock:{},
    }
  },

  computed: {
    ...mapGetters(['allUserInfo'])
  },

  /*beforeRouteEnter(to, from, next){
    next(vm => {
      // 通过 `vm` 访问组件实例
      // 若是有了登录信息则不允许返回欢迎页
      if (vm.allUserInfo.id && to.name === 'welcome'){
        next('/')
      } else {
        next()
      }
    })
  },*/

  created() {
    // 对url进行解构赋值
    const {rpId, gId, p, g,account, cId, cn, st} = this.$route.query || {};
    console.log('created()函数', rpId);

    if (rpId) {
      this.account = this.$Base64.decode(account);
      this.recommendID = this.$route.query.rpId;
      this.companyId = gId || ''
      this.person_state = p*1
      this.group_state = g*1;
      // this.toCompanyPage(this.companyId,this.group_state)
      /*
        * 2022-03-01 新的需求
        * cId为渠道id,
        * cn为渠道名称,
        * cn为来源类型,
        * */

      // cId=${id}&cn=${name}&st=${source_type}
      this.channelId = cId;
      this.channelName = cn;
      this.source_type = st;

    } else {
      // Toast('参数有误。');
      // this.toCompanyPage(this.companyId,this.group_state)
      this.$router.push('/mine');
    }
  },


  mounted() {
    // 获得分享者（中介账号）的用户信息
    this.getStockNum()
    this._getSharerInfo();

  },

  methods: {
    getUserLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
          position => {
            console.log('11111111')
            console.log(position)
            console.log('22222222222')
            this.location = {
              latitude: position.coords.latitude,
              longitude: position.coords.longitude
            };
            this.logAddress()
          },
          error => {
            Toast('请开启您手机定位')
            console.error(error);
          }
        );
      } else {
        console.error("Geolocation is not supported by this browser.");
      }
      if(!this.location){
        Toast('请开启您手机定位')
        return
      }
    },
    //领取股份获取当前位置
    async logAddress(){
      let that = this
      let params = {
          lon:that.location.longitude,
          lat:that.location.latitude
        }
        const res = await that.$api.user.checklonandlat(params)
        console.log(res)
        if(res.data == true){
          that.scancreate()
        }else{
          Toast('当前城市暂无合伙人经营此项目，您可以联系客服合伙经营当前城市，或者去已经营的城市:上海、领取股份。');
        }
    },
    //
    scancreate(){
      let {id}=this.allUserInfo
        let company_id=this.$route.query.company_id
        console.log(stock,'stockstock')
        const pathName = 'unReceivedStockbdyh'
        stock.scancreategf({userId:company_id,scanningUserId:id,sourcetype:sourceTypeObj[this.$route.query.st]}).then().catch(e=>{
          if(e.code==201){
            setTimeout(() => {
                this.$router.push({
                name: pathName,
                  query: {
                    type:1,
                    ...this.$route.query
                  }
                });
            },1500)
        }
          }

       )
    },
    toReceivedStockPage(num, keyId){
      let allCertificate = window.localStorage.getItem('allCertificate')
      // 没有登录凭证跳转登录页
      if (!allCertificate) {
        this.$store.dispatch('logOut')
        Dialog.confirm({
          message: '此功能需要注册登入才能使用，为您跳转到注册登入页面。'
        })
          .then(() => {
            this.$router.push({
              path: `/login?redirect=${this.$route.fullPath}`
            })
          })
          .catch(() => {
            // on cancel
          })
      } else{
        // this.logAddress()
        //this.getUserLocation()
      }
    },
    async getStockNum() {
      const res = await this.$api.others.getInvitatioStockNum();
      if (res.code === 200){
        this.stock = res?.data || 0
      };
    },
    async _getSharerInfo(){
      const resp = await this.$api.user.reqSharerInfo(this.recommendID);
      if(resp.code === 200){
        // 公司信息
        this.companyId = resp.data.company_id;
        // 个人认证的状态
        this.person_state = resp.data.certification_state;
        // 企业认证的状态
        this.group_state = resp.data.company_certification_state;
      }
    },

    handleClickBack(){
      // Dialog.confirm({
      //   title: '温馨提示',
      //   message: '您确定关闭吗？点击确定，可前往软件的首页进行体验。',
      //   messageAlign: 'left',
      // }).then(() => {
      //   this.$router.push('/')
      // })
      //   .catch(() => {
      //   });
    },

    // 添加好友
    add_friend(){
      let allCertificate = window.localStorage.getItem('allCertificate')
      // 没有登录凭证跳转登录页
      if (!allCertificate) {
        this.$store.dispatch('logOut')
        Dialog.confirm({
          message: '此功能需要注册登入才能使用，为您跳转到注册登入页面。'
        })
          .then(() => {
            this.$router.push({
              path: '/login'
            })
          })
          .catch(() => {
            // on cancel
          })
      }else{
        this.$router.push({
          name: 'addFreid',
          params: {
            account_scan: this.account,
            type:'scan'
          }
        })
      }
    },

    toCompanyPage(companyId, group_state){
      console.log('1111111111')
      console.log(companyId)
      console.log(group_state)
      console.log('222222')
      if (companyId && group_state === 2){
          // 需要登录才能关注的
          /*
          let params = {
            company_id: companyId
          };
          let res = await this.$api.job.followCompany(params);
          if (res.code === 200){
            Toast(res.data);
            await this.$router.push(`/company/${companyId}`);
          }
          */
        this.$router.push(`/company/${companyId}?qode=1`);
      } else {
        Dialog.alert({
          title: '温馨提示',
          message: '由于该公司还没有成功完成企业认证，暂时无法关注该公司！！',
          messageAlign: 'left',
        }).then(() => {
          // on confirm
          // this.$router.push('/')
        })
      }
    },

    toRegisterPage(){
      this.$router.push({
        name: 'register',
        query: {
          recommendID: this.recommendID,
          source_channel_id: this.channelId,
          source_channel_name: this.channelName,
          source_type: this.source_type,
        }
      })
    },
    toHelper(){
      this.$router.push({
        name: 'jinpinHelper',
        query: {
          helpIcon: 2,
        }
      })
    }
  },

}
</script>

<style lang="scss" scoped>
.welcome_page{
  /deep/ .hot_operation{
    .van-icon-fire-o::before{
      color: red;
    }
  }
  .wehead{
    background: white;
    padding: 0.52667rem;
    box-sizing: border-box;
    .jinpinHelper{
      margin-top: .45rem;
    }
    .account{
      margin-top:.2rem
    }
  }
}

</style>
